package com.ebupt.migu.music.market.controller;

import com.alibaba.fastjson.JSON;
import com.ebupt.migu.music.common.entity.ResultObject;
import com.ebupt.migu.music.common.exception.MyException;
import com.ebupt.migu.music.common.exception.StatusEnum;
import com.ebupt.migu.music.common.util.CSVUtils;
import com.ebupt.migu.music.common.util.EasyExcelUtil;
import com.ebupt.migu.music.market.dto.MarketSmsCountDTO;
import com.ebupt.migu.music.market.entity.MarketSmsAuditRecord;
import com.ebupt.migu.music.market.service.impl.MarketSmsStrategyServiceImpl;
import com.ebupt.migu.music.market.vo.*;
import com.mysql.cj.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;


@Slf4j
@RestController
@RequestMapping("/market-sms-strategy")
public class MarketSmsController {

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private MarketSmsStrategyServiceImpl marketSmsStrategyService;

    @Autowired
    private HttpServletResponse response;

    @Value("${path.ringtonesId_list_path}")
    private String FILE_UPLOAD_PATH;


    private static String[] propagateArr = {"strategyId", "strategyName", "executeType", "count", "createTime"};
    private static String[] propagateHead = {"策略ID", "策略名称", "状态", "数量", "创建时间"};


    /**
     * 创建策略
     *
     * @return
     */
    @PostMapping("/add")
    public ResultObject add(@RequestBody MarketSmsStrategyVO strategyVO) {
        log.info(">>>>>>>>>>>>>>strategyVO：{}", JSON.toJSONString(strategyVO));
        try {
            return marketSmsStrategyService.addStrategy(strategyVO);
        } catch (MyException e) {
            ResultObject res = new ResultObject();
            res.setCode(e.getStatusEnum().getCode());
            res.setMsg(e.getMessage());
            return res;
        }
    }


    /**
     * 分页、条件查询策略列表
     * 查询条件： 策略名称、创建时间、执行状态、创建人、
     *
     * @return
     */
    @PostMapping("/list")
    public ResultObject strategyList(@RequestBody MarketSmsStrategyPageVO vo) {
        return marketSmsStrategyService.strategyList(vo);
    }


    /**
     * 撤回
     *
     * @return
     */
    @GetMapping("/revocation")
    public ResultObject revocation(String strategyId, String status) {
        return marketSmsStrategyService.revocation(strategyId, status);
    }


    /**
     * 编辑
     *
     * @return
     */
    @PostMapping("/edit")
    public ResultObject strategyEdit(@RequestBody MarketSmsStrategyVO strategyVO) {
        return marketSmsStrategyService.strategyEdit(strategyVO);
    }


    /**
     * 策略明細
     *
     * @return
     */
    @GetMapping("/detail")
    public ResultObject strategyDetail(String strategyId) {
        return marketSmsStrategyService.strategyDetail(strategyId);
    }


    /**
     * 分页、条件查询策略列表
     * 查询条件： 策略名称、创建时间、执行状态、创建人、
     *
     * @return
     */
    @PostMapping("/check-list")
    public ResultObject checkList(@RequestBody MarketSmsAuditPageVO vo) {
        return marketSmsStrategyService.checkList(vo);
    }


    /**
     * 审核
     *
     * @return
     */
    @PostMapping("/check")
    public ResultObject check(@RequestBody MarketSmsAuditRecord vo) {
        return marketSmsStrategyService.check(vo);
    }


    /**
     * 审核记录
     *
     * @return
     */
    @GetMapping("/checkRecord")
    public ResultObject checkRecord(String strategyId) {
        return marketSmsStrategyService.checkRecord(strategyId);
    }


    /**
     * 撤回记录
     *
     * @return
     */
    @GetMapping("/revocationRecord")
    public ResultObject revocationRecord(String strategyId) {
        return marketSmsStrategyService.revocationRecord(strategyId);
    }

    /**
     * 查看短信发送进度
     *
     * @return
     */
    @GetMapping("/checkProgress")
    public ResultObject checkProgress(String strategyId) {
        return marketSmsStrategyService.checkProgress(strategyId);
    }


    /**
     * 删除
     *
     * @return
     */
    @GetMapping("/delete")
    public ResultObject delete(String strategyId) {
        return marketSmsStrategyService.delete(strategyId);
    }


    /**
     * 效果统计
     * 查询条件： 策略名称、创建时间、执行状态、创建人、
     *
     * @return
     */
    @PostMapping("/effectList")
    public ResultObject effectList(@RequestBody MarketSmsCountPageVO vo) {
        return marketSmsStrategyService.effectList(vo);
    }


    /**
     * 导出效果统计
     *
     * @return
     */
    @RequestMapping(value = "/export", produces = MediaType.TEXT_HTML_VALUE)
    public void export(
            @RequestParam String strategyName,
            @RequestParam String creatorName,
            @RequestParam String executeType,
            @RequestParam String sd,
            @RequestParam String ed,
            @RequestParam Integer page,
            @RequestParam Integer pageSize

    ) {
        MarketSmsCountPageVO params = new MarketSmsCountPageVO();
        params.setCreatorName(creatorName);
        params.setSd(sd);
        params.setEd(ed);
        params.setStrategyName(strategyName);
        params.setExecuteType(executeType);
        params.setPage(page);
        params.setPageSize(pageSize);
        List<MarketSmsCountDTO> list = marketSmsStrategyService.export(params);
        EasyExcelUtil.export(response, MarketSmsCountVo.class, list, "挂机短信");

    }

    /**
     * 铃音ID导入
     *
     * @return
     */
    @PostMapping(value = "/ringtonesId/csvImport")
    @ResponseBody
    public ResultObject csvImport(@RequestParam("file") MultipartFile file) {
        // 校验文件是否为空，格式是否正常
        // 限制文件上传类型为csv
        boolean isExcelFile = CSVUtils.validateUploadFile(file, "csv");
        if (!isExcelFile) {
            throw new MyException(StatusEnum.UPLOAD, "文件格式或内容异常！");
        }
        // 限制文件大小
        if (file.getSize() > 20 * 1024 * 1024) {
            throw new MyException(StatusEnum.UPLOAD, "文件大小超过限制,最大不超过20MB！");
        }
        Date date = new Date();
        String timeStr = com.ebupt.migu.music.common.util.DateUtil.parseDateToStr(date, com.ebupt.migu.music.common.util.DateUtil.DATE_TIME_FORMAT_YYYYMMDDHHMISS);
        String newPath = FILE_UPLOAD_PATH + timeStr + "_" + file.getOriginalFilename();
        //上传附件到指定目录
        CSVUtils.upload(file, newPath);
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("fileName", file.getOriginalFilename());
        hashMap.put("filePath", newPath);
        return new ResultObject().ok(hashMap);
    }

}
